/*
' Copyright (c) 2011  DotNetNuke Corporation
'  All rights reserved.
' 
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
' DEALINGS IN THE SOFTWARE.
' 
*/

using System;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Security;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using DotNetNuke.Framework.Providers;
using DotNetNuke.Modules.PersonalAssistants.Components;
using DotNetNuke.Entities.Modules;

namespace DotNetNuke.Modules.PersonalAssistants
{

    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The ViewPersonalAssistants class displays the content
    /// </summary>
    /// -----------------------------------------------------------------------------
    public partial class View : PersonalAssistantsModuleBase//, IActionable
    {
        private const string providerType = "data";
        private ProviderConfiguration providerConfiguration = ProviderConfiguration.GetProviderConfiguration(providerType);
        private string connectionString;
        List<PersonalAssistantProfile> oEntries = new List<PersonalAssistantProfile>();
        List<PersonalAssistantProfile> oEntries2 = new List<PersonalAssistantProfile>();
        FeatureController oController;
        #region Event Handlers
        

        override protected void OnInit(EventArgs e)
        {

            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
        }


        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// -----------------------------------------------------------------------------
        private void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {

                    
                    //Selection criteria
                    Provider provider = (Provider)providerConfiguration.Providers[providerConfiguration.DefaultProvider];
                    connectionString = DotNetNuke.Common.Utilities.Config.GetConnectionString();

                    SqlConnection commonConnection = new SqlConnection();
                    commonConnection.ConnectionString = connectionString;
                    SqlCommand sharedSqlCommand;
                    SqlDataReader sharedSqlDataReader;

                    //PA_EmployerLocation
                    sharedSqlCommand = new SqlCommand("SELECT Name FROM SYCIL_LISTS WHERE ListName = 'LOCATIONS' ORDER BY ListOrder", commonConnection);
                    commonConnection.Open();
                    sharedSqlDataReader = sharedSqlCommand.ExecuteReader();
                    selPA_EmployerLocation.DataSource = sharedSqlDataReader;
                    selPA_EmployerLocation.DataBind();
                    commonConnection.Close();
                    sharedSqlDataReader.Close();

                    //PrimaryTask
                    sharedSqlCommand = new SqlCommand("SELECT Name FROM SYCIL_LISTS WHERE ListName = 'TASKS' ORDER BY ListOrder", commonConnection);
                    commonConnection.Open();
                    sharedSqlDataReader = sharedSqlCommand.ExecuteReader();
                    selPrimaryTask.DataSource = sharedSqlDataReader;
                    selPrimaryTask.DataBind();
                    commonConnection.Close();
                    sharedSqlDataReader.Close();

                    //Secondary task
                    sharedSqlCommand = new SqlCommand("SELECT Name FROM SYCIL_LISTS WHERE ListName = 'TASKS' ORDER BY ListOrder", commonConnection);
                    commonConnection.Open();
                    sharedSqlDataReader = sharedSqlCommand.ExecuteReader();
                    selSecondaryTask.DataSource = sharedSqlDataReader;
                    selSecondaryTask.DataBind();
                    commonConnection.Close();
                    sharedSqlDataReader.Close();

                    //DaysOfWeekRequired
                    sharedSqlCommand = new SqlCommand("SELECT Name FROM SYCIL_LISTS WHERE ListName = 'DAYS' ORDER BY ListOrder", commonConnection);
                    commonConnection.Open();
                    sharedSqlDataReader = sharedSqlCommand.ExecuteReader();
                    selDaysOfWeekRequired.DataSource = sharedSqlDataReader;
                    selDaysOfWeekRequired.DataBind();
                    commonConnection.Close();
                    sharedSqlDataReader.Close();

                    PersonalAssistantsView.DataSource = GetDataSourceForPAView();
                    PersonalAssistantsView.DataBind();
                }


            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
        protected void PersonalAssistantsView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (PersonalAssistantsView.SelectedIndex != -1)
            {
                PersonalAssistantProfile oProfile = new PersonalAssistantProfile();
                oController = new FeatureController();
                object paModuleIdForDB = Settings["PersonalAssistantsModuleIDforDB"];
                if (paModuleIdForDB != null)
                {
                    int paModuleId = int.Parse(paModuleIdForDB.ToString());
                    oProfile = oController.GetPAProfile(paModuleId, int.Parse(PersonalAssistantsView.SelectedDataKey.Value.ToString()));

                    System.Text.StringBuilder oDisplay = new System.Text.StringBuilder(Localization.GetString("PAProfileInformation", this.LocalResourceFile));
                    oDisplay.Replace("[ALITTLEBITABOUTMYSELF]", oProfile.ALittleBitAboutMyself);
                    oDisplay.Replace("[BARREDBYISA]", oProfile.BarredByISA);
                    oDisplay.Replace("[CAROWNER]", oProfile.CarOwner);
                    oDisplay.Replace("[DATEOFPAUPDATE]", oProfile.DateOfPAUpdate.ToString());
                    oDisplay.Replace("[DATETIME]", oProfile.DateTime.ToString());
                    oDisplay.Replace("[AVAILABLEDAYS]", oProfile.DaysAvailable);
                    oDisplay.Replace("[DAYSPERWEEK]", oProfile.DaysPerWeek);
                    oDisplay.Replace("[DRIVINGLICENCE]", oProfile.DrivingLicenceHeld);
                    oDisplay.Replace("[ECRWILLING]", oProfile.ECRWilling);
                    oDisplay.Replace("[EMAIL]", oProfile.Email);
                    oDisplay.Replace("[EMERGENCYCALLOUT]", oProfile.EmergencyCallout);
                    oDisplay.Replace("[HOURSPERDAY]", oProfile.HoursPerDay);
                    oDisplay.Replace("[PERSONALASSISTANT]", oProfile.IsPersonalAssistant);
                    oDisplay.Replace("[LANGUAGES]", oProfile.Languages);
                    oDisplay.Replace("[LATENIGHTS]", oProfile.LateNights);
                    oDisplay.Replace("[LOCATIONS]", oProfile.Locations);
                    oDisplay.Replace("[MALEORFEMALE]", oProfile.MaleOrFemale);
                    oDisplay.Replace("[MEATPRODUCTS]", oProfile.MeatProducts);
                    oDisplay.Replace("[OVERNIGHTWAKINGNIGHTS]", oProfile.OvernightWakingNights);
                    oDisplay.Replace("[PALOCATION]", oProfile.PALocation);
                    oDisplay.Replace("[PEMISSIONFORUK]", oProfile.PermissionForUK);
                    oDisplay.Replace("[PROFILEAPPROVED]", oProfile.ProfileApproved);
                    oDisplay.Replace("[REFERENCES]", oProfile.Provide2References);
                    oDisplay.Replace("[PUBLISH]", oProfile.PublishThisProfile);
                    oDisplay.Replace("[REFERENCENOTES]", oProfile.ReferenceNotes);
                    oDisplay.Replace("[SCHOOLHOLIDAYS]", oProfile.SchoolHolidays);
                    oDisplay.Replace("[SERVICEREQUIRED]", oProfile.ServiceRequired);
                    oDisplay.Replace("[SKILLNOTES]", oProfile.SkillNotes);
                    oDisplay.Replace("[SMOKER]", oProfile.Smoker);
                    oDisplay.Replace("[TASKNOTES]", oProfile.TaskNotes);
                    oDisplay.Replace("[TASKS]", oProfile.Tasks);
                    oDisplay.Replace("[TERMTIME]", oProfile.TermTime);
                    oDisplay.Replace("[AVAILABLEHOURS]", oProfile.TimesAvailable);
                    oDisplay.Replace("[USERNAME]", oProfile.Username);
                    oDisplay.Replace("[WORKPATTERNNOTES]", oProfile.WorkpatternNotes);
                    oDisplay.Replace("[YEARSATADDRESS]", oProfile.YearsResident);
                    lblPAProfileInformation.Text = oDisplay.ToString();
                    PersonalAssistantsMultiView.ActiveViewIndex = 1;
                }
            }
          
        }

        protected void btnRefreshPAView(object sender, EventArgs e)
        {
            PersonalAssistantsView.DataSource = GetDataSourceForPAView();
            PersonalAssistantsView.DataBind();

        }
        protected void btnClearCriteria(object sender, EventArgs e)
        {
            selPA_EmployerLocation.SelectedIndex = 0;
            selPrimaryTask.SelectedIndex = 0;
            selSecondaryTask.SelectedIndex = 0;
            selDaysOfWeekRequired.SelectedIndex = 0;
            PersonalAssistantsView.DataSource = GetDataSourceForPAView();
            PersonalAssistantsView.DataBind();

        }
        protected void PersonalAssistantsView_PageIndexChanged(object sender, EventArgs e)
        {

        }
        protected void returnToTheHomePage(object sender, EventArgs e)
        {
           

            object paHomePageUrl = Settings["PersonalAssistantsHomePageUrl"];
            if (paHomePageUrl != null)
            {
                Response.Redirect(paHomePageUrl.ToString(), true);
            }
        }
        protected List<PersonalAssistantProfile> GetDataSourceForPAView()
        {
            object paModuleIdForDB = Settings["PersonalAssistantsModuleIDforDB"];
            if (paModuleIdForDB != null)
            {
                int paModuleId = int.Parse(paModuleIdForDB.ToString());
                oController = new FeatureController();
                // assume PA Employer is using this 
                oEntries = oController.GetApprovedEntries(paModuleId);
                
                foreach( PersonalAssistantProfile p in oEntries ){
                    bool copy = true;
                    // Match for Employer Location - if selected and no match, don't copy
                    if((!selPA_EmployerLocation.SelectedIndex.Equals((int)0)) && (!p.Locations.Contains(selPA_EmployerLocation.SelectedValue.ToString())))
                        copy = false;
                    // Match for Primary task - if selected and no match, don't copy
                    if((!selPrimaryTask.SelectedIndex.Equals((int)0)) && (!p.Tasks.Contains(selPrimaryTask.SelectedValue.ToString())))
                        copy = false;
                    // Match for Secondary task ...
                    if((!selSecondaryTask.SelectedIndex.Equals((int)0)) && (!p.Tasks.Contains(selSecondaryTask.SelectedValue.ToString())))
                        copy = false;
                    // Match for Day required
                    if ((!selDaysOfWeekRequired.SelectedIndex.Equals((int)0)) && (!p.DaysAvailable.Contains(selDaysOfWeekRequired.SelectedValue.ToString())))
                        copy = false;
                    if (copy)
                        oEntries2.Add((PersonalAssistantProfile) p);
                }
            }
            lblRecordCount.Text = "Record count with the current criteria is " + oEntries2.Count.ToString();
            return oEntries2;
        }
        protected void PersonalAssistantsView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            object paModuleIdForDB = Settings["PersonalAssistantsModuleIDforDB"];
            if (paModuleIdForDB != null)
            {
                int paModuleId = int.Parse(paModuleIdForDB.ToString());
                oController = new FeatureController();
                oEntries = oController.GetAllEntries(paModuleId);
                PersonalAssistantsView.DataSource = GetDataSourceForPAView();

                PersonalAssistantsView.PageIndex = e.NewPageIndex;
                PersonalAssistantsView.DataBind();

            }
        }


        #endregion

        #region Optional Interfaces

        //public ModuleActionCollection ModuleActions
        //{
        //    get
        //    {
        //        ModuleActionCollection Actions = new ModuleActionCollection();
        //        Actions.Add(GetNextActionID(), Localization.GetString("EditModule", this.LocalResourceFile), "", "", "", EditUrl(), false, SecurityAccessLevel.Edit, true, false);
        //        return Actions;
        //    }
        //}

        #endregion



    }

}
